<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author: zl
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\crm\model\BalanceLog;
use app\crm\model\Setting;
use app\crm\model\SettingCategory;
use app\crm\model\Service;
use app\crm\model\ReturnVist;
use app\crm\model\ReturnVistT;
use app\crm\model\Customer as CustomerModel;
use app\crm\model\TransferShop;
use app\mini\model\MiniPrizeLog;
use app\mini\model\SysModelMini;
use app\crm\model\MiniProgramModel;
use app\crm\model\CustomerConfig as CustomerConfigModel;
use app\crm\model\CustomerGrade as CustomerGradeModel;
use app\mini\validate\MiniProgramValidate;
use think\exception\ValidateException;
use think\response\Json;
use think\facade\Db;
use Kingdee\Kingdee;


class MiniProgram extends ApiCommon
{
    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
     **/
    public function initialize()
    {
        $action = [
            'permission' => ['house_list','setcustomerage','setzycustomer','dsmonth','setmonth'],
            'allow' => ['users', 'info']
        ];
        event('CheckAuth',$action);
        $request = $this->request;
        $a = strtolower($request->action());

        $this->customerModel = new CustomerModel();
        $this->customerConfigModel = new CustomerConfigModel();
        if (!in_array($a, $action['permission'])) {
            parent::initialize();
        }
    }

    public function evaluationList(): Json
    {
        $param = request()->param();

        $model = new MiniProgramModel();

        $data = $model->getEvaluationList($param);

        $is_export = $param['is_export'] ?? '';

        if($is_export == '1'){

            $title = '服务评价明细导出';

            $callName = [

                'customer_name' => '姓名',

                'tel' => '电话',

                'shop_name' => '门店',

                'score_amount' => '评价分数',

                'rate_text' => '评价详情',

                'create_time' => '评价时间',

            ];

            $downUrl = exportExcelData($title,$callName,$data['list'],'xlsx',1);

            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

            exit;


        }


        return resultArray(['error' => '获取成功', 'data'=>$data]);

    }

    public function feedbackList(): Json
    {

        $param = request()->param();

        $model = new MiniProgramModel();

        $data = $model->getFeedbackList($param);

        $is_export = $param['is_export'] ?? '';

        if($is_export == '1'){

            $title = '反馈明细导出';

            $callName = [

                'customer_name' => '姓名',

                'tel' => '电话',

                'shop_name' => '门店',

                'type' => '反馈类型',

                'feed_back_value' => '反馈内容',

                'create_time' => '提交时间',

            ];

            $downUrl = exportExcelData($title,$callName,$data['list'],'xlsx',1);

            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

            exit;


        }

        return resultArray(['error' => '获取成功', 'data'=>$data]);

    }

    public function manyiduList(): Json
    {

        $param = request()->param();

        $model = new MiniProgramModel();

        $data = $model->getManyiduList($param);

        $is_export = $param['is_export'] ?? '';

        if($is_export == '1'){

            // echo "<pre>";
            // print_r($data);
            // echo "</pre>";
            // exit;

            $title = '满意度明细导出';

            $downUrl = exportExcelData($title,$data['callName'],$data['list'],'xlsx',1);

            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

            exit;


        }

        return resultArray(['error' => '获取成功', 'data'=>$data]);

    }

    public function getAnswers(): Json
    {

        $param = request()->param();

        $model = new MiniProgramModel();

        $data = $model->getAnswers($param);

        $is_export = $param['is_export'] ?? '';

        return resultArray(['error' => '获取成功', 'data'=>$data]);

    }

    public function getBannerList(): Json
    {

        $param = request()->param();

        $model = new MiniProgramModel();

        $data = $model->getBannerList($param);

        return resultArray(['error' => '获取成功', 'data'=>$data]);

    }

    public function addBanner(): Json
    {

        $param = request()->param();

        $model = new MiniProgramModel();

        $data = $model->addBanner($param);

        return resultArray(['error' => $data['error'], 'data'=>$data['id']]);

    }


    public function changBannerStatus(): Json
    {

        $param = request()->param();

        $model = new MiniProgramModel();

        $data = $model->changBannerStatus($param);

        return resultArray(['error' => $data['error'], 'data'=>$data['id']]);

    }

    /**
     * 获取小程序抽奖活动列表
     *
     * @return Json
     */

    public function getMiniEventList()
    {
        $request = request()->param();
        $where = [];
        if(!empty($request['name']))
        {
            array_push($where,['name','like','%'.$request['name'].'%']);
        }
        $total = Db::name('mini_prize_event')->where($where)->count();
        $result = Db::name('mini_prize_event')->where($where);
        if(!empty($request['page'])&&!empty($request['limit']))
        {
            $result = $result->limit(($request['page'] - 1) * $request['limit'], $request['limit']);
        }
        $result = $result->select()->toArray();
        foreach ($result as $key => $value)
        {
            if($value['start_time']==0)
            {
                $result[$key]['start_time']="无开始日期";
            }else{
                $result[$key]['start_time']=date('Y-m-d H:i:s',$value['start_time']);
            }
            if($value['end_time']==0)
            {
                $result[$key]['end_time']="无开始日期";
            }else{
                $result[$key]['end_time']=date('Y-m-d H:i:s',$value['end_time']);
            }
        }

        return $this->success(['list'=>$result],"获取完成",$total);
    }

    /**
     * 获取小程序抽奖活动详情
     *
     * @return Json
     */
    public function  getMiniEventPrizeDetail()
    {
        $request = request()->param();
        $id = $request['event_id'];
        $where = [];
        array_push($where,['event_id','=',$id]);
        $result = Db::name('mini_prize')->where($where)->order('position')->select()->toArray();
        foreach ($result as $key => $value)
        {
            $result[$key]['probability'] = ($value['probability']/10);

        }
        return $this->success(['list'=>$result],"获取完成");
    }

    /**
     * 获取奖品内容
     *
     * @return Json
     */
    public function getObject()
    {
        $request = request()->param();
        $type = $request['type']??0;
        if($type != 3)
        {
            $where = [];
            array_push($where,['type','=',$type]);
            array_push($where,['status','=',1]);
            $result = Db::name('customer_point_goods')->where($where)->select()->toArray();
        }else{
            $where = [];
            array_push($where,['change_type','=',1]);
            array_push($where,['status','=',1]);
            $result = Db::name('customer_point_origin')->field('id,message as goods_name')->where($where)->select()->toArray();

        }
        return $this->success(['list'=>$result],"获取完成");
    }

    /**
     * 更新奖品
     *
     * @return Json
     */
    public function updatePrize()
    {
        $request = request()->param();
        try {
            validate(MiniProgramValidate::class)
                ->scene('updatePrize')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }
        $data['probability'] = $request['probability']*10;
        $data=[
            'probability'=>$request['probability']*10,
            'name'=>$request['name']??'',
            'type'=>$request['type'],
            'object'=>$request['object']??0,
            'url'=>$request['url']??"",
            'status'=>$request['status']??0,
            'position'=>$request['position']??0,
            'event_id'=>$request['event_id']??0,
        ];
        $position = Db::name('mini_prize')->where([
            ['event_id','=',$data['event_id']],
            ['position','=',$data['position']]
        ])->find();
        if(!empty($position))
        {
            $position['position']=0;
            Db::name('mini_prize')->update($position);
        }
        if(!empty($request['id']))
        {
            $data['id'] = $request['id'];
            $res = Db::name('mini_prize')->update($data);
        }else{
            $res = Db::name('mini_prize')->insert($data);
        }
        if(!$res)
        {
            return $this->failed("编辑失败");
        }else{
            return $this->success([],"编辑成功");
        }
    }

    /**
     * 获取抽奖记录
     *
     * @return Json
     */
    public function getPrizeLog()
    {
        $request = request()->param();
        $where = [];
        if(!empty($request['event_id']))
        {
            array_push($where,['a.event_id','=',$request['event_id']]);
        }
        if(!empty($request['customer_name']))
        {
            array_push($where,['c.customer_name','like','%'.$request['customer_name'].'%']);
        }
        $data = DB::name('mini_prize_log')->alias('a')
            ->join('mini_prize b','a.prize_id=b.id','left')
            ->join('customer c','a.customer_id=c.id','left')
            ->join('mini_prize_event d','a.event_id=d.id','left')
            ->where($where)
            ->field('a.id,b.name,d.name as event_name,c.customer_name,a.created_at,a.prize_id');
        $total = $data->count();
        $data = $data->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
            ->order('a.created_at','desc')
            ->select()->toArray();
        foreach ($data as $key => $value)
        {
            $data[$key]['created_at']=date('Y-m-d H:i:s',$value['created_at']);
            if($value['prize_id'] == 0)
            {
                $data[$key]['name']="未中奖";
            }
        }
        return $this->success(['list'=>$data], '获取成功',$total);
    }

    /**
     * 修改或添加小程序抽奖活动
     *
     * @return Json
     */
    public function updateMiniPrizeEvent()
    {
        $request = request()->param();
        if(!empty($request['id']))
        {
            $event = Db::name('mini_prize_event')->where('id','=',$request['id'])->find();
            if(empty($event))
            {
                return $this->failed("活动不存在");
            }
        }
        $data = [
            'name'=>$request['name']??"",
            'start_time'=>strtotime($request['start_time'])??0,
            'end_time'=>strtotime($request['end_time'])??0
        ];
        if(!empty($request['id']))
        {
            $data['id'] = $request['id'];
            $res = Db::name('mini_prize_event')->update($data);
        }else{
            $res = Db::name('mini_prize_event')->insert($data);
        }
        if(!$res)
        {
            return $this->failed("编辑失败");
        }else{
            return $this->success([],"编辑成功");
        }
    }

    /** 修改活动状态
     *
     * @return Json
     */
    public function updateMiniPrizeEventStatus()
    {
        $request = request()->param();
        if(empty($request['id']))
        {
            return $this->failed("id错误");
        }
        $id = $request['id'];
        $event = Db::name('mini_prize_event')->where('id','=',$id)->find();
        if(empty($event))
        {
            return $this->failed("活动不存在");
        }
        $data=['id'=>$id];
        if($event['status']==1)
        {
            $data['status']=0;
        }else{
            $data['status']=1;
        }
        $res = Db::name('mini_prize_event')->update($data);
        if(!$res)
        {
            return $this->failed("编辑失败");
        }else{
            return $this->success([],"编辑成功");
        }
    }

    /** 修改活动状态
     *
     * @return Json
     */
    public function questionList()
    {

        $param = request()->param();

        $wenjuan = $param['wenjuan'] ?? '1';

        $list = Db::name('service_log_questions')->where('wenjuan',$wenjuan)->column('title');
        
        return resultArray(['error' => '啦啦啦', 'data'=>$list]);
    }


}
